package com.jhd.fuzhou.view.daily;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.google.gson.Gson;
import com.jhd.fuzhou.util.AnswerUtil;
import com.jhd.fuzhou.util.EditTextView;
import com.jhd.fuzhou.view.login.BaseActivity;
import com.jhd.fuzhou.R;
import com.jhd.fuzhou.service.SupervisionService;
import com.jhd.fuzhou.util.CustomToast;
import com.jhd.fuzhou.util.TextDialog;
import com.jhd.fuzhou.util.UtilHelper;
import com.jhd.fuzhou.vo.CheckValue;
import com.jhd.fuzhou.vo.DetectedItemsVo;
import com.jhd.fuzhou.vo.IllegalRecordDtlVo;
import com.jhd.fuzhou.vo.InspectResultVo;
import com.jhd.fuzhou.vo.JsonForResult;
import com.jhd.fuzhou.vo.QuestionBankOptionVo;
import com.jhd.fuzhou.vo.SupervisionInspectionContentVo;
import com.jhd.fuzhou.vo.Supervisor;

import net.zigin.commons.util.ParamsMapUtil;
import net.zigin.commons.util.StringUtil;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import static com.jhd.fuzhou.view.login.MainActivity.supervisionInspectionVo;

/*第三步检查记录*/
public class DailyStepThreeActivity extends BaseActivity {
    private Context context= DailyStepThreeActivity.this;
    private List<SupervisionInspectionContentVo> supervisionInspectionContentList=null;
    @BindView(R.id.rv_question_tree)RecyclerView rv_question_tree;
    @BindView(R.id.tv_specialityDetail)TextView tv_specialityDetail;
    @BindView(R.id.tv_illegal_num)TextView tv_illegal_num;
    @BindView(R.id.btn_back)Button btn_back;
    @BindView(R.id.btn_next)Button btn_next;
    @BindView(R.id.rb_status_1)RadioButton rb_status_1;
    @BindView(R.id.rb_status_2)RadioButton rb_status_2;
    @BindView(R.id.rb_status_3)RadioButton rb_status_3;
    @BindView(R.id.rb_status_4)RadioButton rb_status_4;
    @BindView(R.id.tv_supervision)TextView tv_supervision;
    @BindView(R.id.rel_quick_check)RelativeLayout rel_quick_check;
    @BindView(R.id.rel_laboratory_check)RelativeLayout rel_laboratory_check;
    @BindView(R.id.lin_illegal)LinearLayout lin_illegal;
    @BindView(R.id.et_supervision)EditText et_supervision;
    @BindView(R.id.et_check_record)EditText et_check_record;
    @BindView(R.id.tv_laboratory_check)TextView tv_laboratory_check;
    @BindView(R.id.tv_quick_check)TextView tv_quick_check;
    private AlertDialog _alertDialog=null;
    private CheckValue checkValue=null;
    private List<DetectedItemsVo> detectedItemsVoList=new ArrayList<>();//所有的检测
    private List<DetectedItemsVo> detectedItemsVoList1=new ArrayList<>();//快速检测
    private List<DetectedItemsVo> detectedItemsVoList2=new ArrayList<>();//实验室检测
    private ProgressDialog _dialog;
    private QuestionTreeAdapter recyclerAdapter;

    @Override
    protected void loadViewLayout() {
        setContentView(R.layout.activity_step_three);
    }

    @Override
    protected void processLogic() {
        application.addStepActivity(this);
        getQuestion();
        getCheckValue();
        findViewById(R.id.iv_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onBackPressed();
            }
        });
        tv_specialityDetail.setText(supervisionInspectionVo.getSpecialityDetail());
        et_supervision.setText((StringUtil.isNullOrEmpty(supervisionInspectionVo.getSupervisionOpinions())?"":supervisionInspectionVo.getSupervisionOpinions()));
        et_check_record.setText((StringUtil.isNullOrEmpty(supervisionInspectionVo.getInspectRecords())?"":supervisionInspectionVo.getInspectRecords()));
    }

    @Override
    protected void onStart() {
        super.onStart();
        upUi();
    }
    private void upUi(){
        if(!StringUtil.isNullOrEmpty(supervisionInspectionVo.getPunish())){
            if("0".equals(supervisionInspectionVo.getPunish())){
                rb_status_4.setChecked(true);
            }else if("1".equals(supervisionInspectionVo.getPunish())){
                rb_status_3.setChecked(true);
            }
        }
        if(supervisionInspectionVo.getIllegalRecordDtlVoList()!=null){
            List<IllegalRecordDtlVo> illegalRecordDtlVoList =supervisionInspectionVo.getIllegalRecordDtlVoList();
            tv_illegal_num.setText(String.valueOf(supervisionInspectionVo.getIllegalRecordDtlVoList().size()));
            if(illegalRecordDtlVoList.size()>0){
                if("公共场所卫生监督科".equals(application.getDeptName())){
                    tv_supervision.setVisibility(View.VISIBLE);
                }
                String basis="";
                for (IllegalRecordDtlVo illegalRecordDtlVo : illegalRecordDtlVoList) {
                    if(basis.equals("")){
                        basis= illegalRecordDtlVo.getSuperviseOpinion();
                    }else{
                        basis=basis+"\n"+ illegalRecordDtlVo.getSuperviseOpinion();
                    }
                }
                tv_supervision.setText(basis);
            }else{
                tv_supervision.setVisibility(View.GONE);
            }
        }else{
            if(!StringUtil.isNullOrEmpty(supervisionInspectionVo.getId())){
                getIllegalRecordDtlById();
            }else{
                tv_supervision.setVisibility(View.GONE);
            }
        }
        if(supervisionInspectionVo.getDetectedItemsVoList()!=null){
            detectedItemsVoList1.clear();detectedItemsVoList2.clear();
            detectedItemsVoList= supervisionInspectionVo.getDetectedItemsVoList();
            for (DetectedItemsVo detectedItemsVo : detectedItemsVoList) {
                if(detectedItemsVo.getCheckType().equals("0")){
                    detectedItemsVoList1.add(detectedItemsVo);
                }else if(detectedItemsVo.getCheckType().equals("1")){
                    detectedItemsVoList2.add(detectedItemsVo);
                }
            }
            if(detectedItemsVoList1.size()>0){
                tv_quick_check.setTextColor(getResources().getColor(R.color.black));
                tv_quick_check.setText("已检测");
            }else{
                tv_quick_check.setTextColor(getResources().getColor(R.color.search));
                tv_quick_check.setText("未检测");
            }
            if(detectedItemsVoList2.size()>0){
                tv_laboratory_check.setTextColor(getResources().getColor(R.color.black));
                tv_laboratory_check.setText("已检测");
            }else{
                tv_laboratory_check.setTextColor(getResources().getColor(R.color.search));
                tv_laboratory_check.setText("未检测");
            }
        }
    }
    private void getIllegalRecordDtlById(){
        Retrofit retrofit = UtilHelper.retrofit(application, UtilHelper.baseUrls.API());//URL的头
        SupervisionService vs = retrofit.create(SupervisionService.class);
        Map<String, String> params = ParamsMapUtil.getInstance("id",supervisionInspectionVo.getId());
        Call<JsonForResult> jsonForResultCall = vs.getIllegalRecordDtlById(application.getAccessToken(), params);
        jsonForResultCall.enqueue(new Callback<JsonForResult>() {
            @Override
            public void onResponse(Call<JsonForResult> call, Response<JsonForResult> response) {
                try {
                    JsonForResult jsonForResult = response.body();
                    if (jsonForResult != null && jsonForResult.isSuccess()) {
                        //请求授权信息
                        if(jsonForResult.getData()!=null){
                            List<IllegalRecordDtlVo> illegalRecordDtlVoList= JSON.parseArray(jsonForResult.getData().toString(), IllegalRecordDtlVo.class);
                            supervisionInspectionVo.setIllegalRecordDtlVoList(illegalRecordDtlVoList);
                            if(illegalRecordDtlVoList!=null&&illegalRecordDtlVoList.size()>0){
                                if("公共场所卫生监督科 ".equals(application.getDeptName())){
                                    tv_supervision.setVisibility(View.VISIBLE);
                                }
                                String basis="";
                                for (IllegalRecordDtlVo illegalRecordDtlVo : illegalRecordDtlVoList) {
                                    if(basis.equals("")){
                                        basis= illegalRecordDtlVo.getSuperviseOpinion();
                                    }else{
                                        basis=basis+"\n"+ illegalRecordDtlVo.getSuperviseOpinion();
                                    }
                                }
                                tv_supervision.setText(basis);
                            }else{
                                tv_supervision.setVisibility(View.GONE);
                            }
                        }
                    }
                } catch (Exception e) {
                    UtilHelper.alertMsg(context, "错误", e.getMessage());
                }
            }
            @Override
            public void onFailure(Call<JsonForResult> call, Throwable t) {
                String msg = "获取违法记录失败!";
                UtilHelper.alertMsg(context, "错误", msg);
            }
        });
    }

    @OnClick({R.id.btn_next,R.id.btn_back,R.id.rel_quick_check,R.id.rel_laboratory_check,R.id.rb_status_3,R.id.rb_status_4,R.id.lin_illegal,R.id.et_supervision,R.id.et_check_record})
    public void onClick(View v){
        Gson gson = new Gson();
        switch (v.getId()){
            case R.id.btn_next:
                next();
                break;
            case R.id.et_supervision:
                TextDialog.showDialog(context,"监督意见",et_supervision);
                break;
            case R.id.et_check_record:
                TextDialog.showDialog(context,"检查记录",et_check_record);
                break;
            case R.id.btn_back:
                onBackPressed();
                break;
            case R.id.rel_quick_check:
                if(checkValue==null){
                    getCheckValue();
                }else{
                    Intent intent1=new Intent(context, DailyQuickCheckActivity.class);
                    intent1.putExtra("checkValue",gson.toJson(checkValue));
                    startActivity(intent1);
                }
                break;
            case R.id.rel_laboratory_check:
                if(checkValue==null){
                    getCheckValue();
                }else {
                    Intent intent2 = new Intent(context, DailyLaboratoryCheckActivity.class);
                    intent2.putExtra("checkValue", gson.toJson(checkValue));
                    startActivity(intent2);
                }
                break;
            case R.id.rb_status_3://处罚1
                supervisionInspectionVo.setPunish("1");
                break;
            case R.id.rb_status_4://不处罚0
                supervisionInspectionVo.setPunish("0");
                break;
            case R.id.lin_illegal:
                startActivity(new Intent(context, DailyIllegalBehaviorActivity.class));
                break;

        }
    }
    public void next(){
        boolean isAll=true;
        for (SupervisionInspectionContentVo supervisionInspectionContentVo : supervisionInspectionContentList) {
            if(supervisionInspectionContentVo.getQuestionBankOptionVoList()!=null&&supervisionInspectionContentVo.getQuestionBankOptionVoList().size()!=0){
                if(StringUtil.isNullOrEmpty(supervisionInspectionContentVo.getQuestionBankOptionId())){
                    CustomToast.showText(context,"还有未选择的问题!",3000,0,0).show();
                    isAll=false;
                    break;
                }
            }
        }
        if(!rb_status_3.isChecked()&&!rb_status_4.isChecked()){
            CustomToast.showText(context,"还未选择是否处罚!",3000,0,0).show();
        }else{
            if(isAll){
                String checkRecord=et_check_record.getText().toString();
                String supervision=et_supervision.getText().toString();
                if(!StringUtil.isNullOrEmpty(checkRecord)){
                    supervisionInspectionVo.setInspectRecords(checkRecord);
                } else{
                    supervisionInspectionVo.setInspectRecords(null);
                }
                if(!StringUtil.isNullOrEmpty(supervision)){
                    supervisionInspectionVo.setSupervisionOpinions(supervision);
                }else{
                    supervisionInspectionVo.setSupervisionOpinions(null);
                }
                supervisionInspectionVo.setSupervisionInspectionContentList(supervisionInspectionContentList);
                Intent intent=new Intent(context, DailyStepFourActivity.class);
                startActivity(intent);
            }
        }
    }

    private void getCheckValue(){
        Retrofit retrofit = UtilHelper.retrofit(application, UtilHelper.baseUrls.UC());//URL的头
//        Retrofit retrofit = UtilHelper.retrofit(application, "http://192.168.1.69:9004/");//URL的头
        SupervisionService vs = retrofit.create(SupervisionService.class);
        JSONArray jsonArray=new JSONArray();
        jsonArray.add("检测项目");
        Map<String, Object> params = new LinkedHashMap<String, Object>();
        params.put("nameList",jsonArray);
        RequestBody requestBody = RequestBody.create(MediaType.parse("Content-Type, application/json"),
                JSON.toJSONString(params));
        Call<JsonForResult> jsonForResultCall = vs.getValueList(application.getAccessToken(), requestBody);
        jsonForResultCall.enqueue(new Callback<JsonForResult>() {
            @Override
            public void onResponse(Call<JsonForResult> call, Response<JsonForResult> response) {
                try {
                    JsonForResult jsonForResult = response.body();
                    if (jsonForResult != null && jsonForResult.isSuccess()) {
                        //请求授权信息
                        if(jsonForResult.getData()!=null){
                            checkValue= JSON.parseArray(jsonForResult.getData().toString(), CheckValue.class).get(0);
                        }
                    }
                } catch (Exception e) {
                    UtilHelper.alertMsg(context, "错误", e.getMessage());
                }
            }
            @Override
            public void onFailure(Call<JsonForResult> call, Throwable t) {
                String msg = "获取检测项目失败!";
                UtilHelper.alertMsg(context, "错误", msg);
            }
        });
    }
    /*获取题库*/
    private void getQuestion(){
        _dialog = new ProgressDialog(context);
        _dialog.setCancelable(false);
        _dialog.setMessage("正在监督问题列表,请稍等...");
        _dialog.show();
        Retrofit retrofit = UtilHelper.retrofit(application, UtilHelper.baseUrls.API());//URL的头
        SupervisionService vs = retrofit.create(SupervisionService.class);
        Map<String, String> params = ParamsMapUtil.getInstance("questionType","监督检查题库").addParam("specialityCategory",(supervisionInspectionVo.getSpecialityCategory()==null)?"": supervisionInspectionVo.getSpecialityCategory());
        Call<JsonForResult> jsonForResultCall = vs.getSuperviseQuestionAndOption(application.getAccessToken(),params);//调用接口获取json返回
        jsonForResultCall.enqueue(new Callback<JsonForResult>() {
            @Override
            public void onResponse(Call<JsonForResult> call, Response<JsonForResult> response) {
                if(_dialog != null)_dialog.cancel();
                try {
                    JsonForResult jsonForResult = response.body();
                    if (jsonForResult != null && jsonForResult.isSuccess()) {
                        //请求授权信息
                        supervisionInspectionContentList= JSON.parseArray(jsonForResult.getData().toString(), SupervisionInspectionContentVo.class);
                        if(supervisionInspectionContentList!=null){
                            LinearLayoutManager linearLayoutManager = new LinearLayoutManager(context);
                            rv_question_tree.setLayoutManager(linearLayoutManager);
                            /*int titleLevel=-1;
                            for (SupervisionInspectionContentVo supervisionInspectionContentVo : supervisionInspectionContentList) {
                                if(supervisionInspectionContentVo.getAllowValue()!=null){
                                    titleLevel=supervisionInspectionContentVo.getLevel()-1;
                                    break;
                                }
                            }*/
                            recyclerAdapter=new QuestionTreeAdapter(supervisionInspectionContentList);
                            rv_question_tree.setAdapter(recyclerAdapter);
                        }
                    }
                } catch (Exception e) {
                    UtilHelper.alertMsg(context, "错误", e.getMessage());
                }
            }
            @Override
            public void onFailure(Call<JsonForResult> call, Throwable t) {
                if(_dialog != null)_dialog.cancel();
                String msg = "获取题库失败!";
                UtilHelper.alertMsg(context, "错误", msg);
            }
        });
    }
    public void changeStatus(Context context, List<SupervisionInspectionContentVo> supervisionInspectionContentList, SupervisionInspectionContentVo supervisionInspectionContentVo) {
        LayoutInflater mLayoutInflater = LayoutInflater.from(context);
        View view = mLayoutInflater.inflate(R.layout.dialog_change_choose, null);
        final androidx.appcompat.app.AlertDialog.Builder alertBuilder = new AlertDialog.Builder(context, R.style.ActionSheetDialogStyle);
        alertBuilder.setView(view);
        AlertDialog _alertDialog = alertBuilder.create();
        //获取当前Activity所在的窗体
        Window window = _alertDialog.getWindow();
        window.setGravity(Gravity.CENTER);
        _alertDialog.show();
        ImageView iv_dismiss = (ImageView) view.findViewById(R.id.iv_dismiss);
        RecyclerView rv_choose = (RecyclerView) view.findViewById(R.id.rv_choose);
        LinearLayoutManager layoutManage = new LinearLayoutManager(context);
        rv_choose.setLayoutManager(layoutManage);
        List<QuestionBankOptionVo> questionBankOptionVoList=new ArrayList<>();
        for (SupervisionInspectionContentVo inspectionContentVo : supervisionInspectionContentList) {
            if(inspectionContentVo.getParentId().equals(supervisionInspectionContentVo.getId())){
                questionBankOptionVoList=inspectionContentVo.getQuestionBankOptionVoList();
            }
        }
        QuestionBankOptionVoAdapter recyclerAdapter=new QuestionBankOptionVoAdapter(_alertDialog,questionBankOptionVoList,supervisionInspectionContentVo);
        rv_choose.setAdapter(recyclerAdapter);
        iv_dismiss.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                _alertDialog.dismiss();
            }
        });
        WindowManager.LayoutParams params = window.getAttributes() ;
        params.width =(int) (((Activity)context).getWindowManager().getDefaultDisplay().getWidth());                     //使用这种方式更改了dialog的框宽
        window.setAttributes(params);
    }

    public class QuestionBankOptionVoAdapter extends RecyclerView.Adapter<QuestionBankOptionVoAdapter.ViewHolder> {
        private List<QuestionBankOptionVo> questionBankOptionVoList;
        private SupervisionInspectionContentVo supervisionInspectionContentVo;AlertDialog _alertDialog;
        public QuestionBankOptionVoAdapter( AlertDialog _alertDialog,List<QuestionBankOptionVo> questionBankOptionVoList,SupervisionInspectionContentVo supervisionInspectionContentVo) {
            this.questionBankOptionVoList = questionBankOptionVoList;
            this.supervisionInspectionContentVo = supervisionInspectionContentVo;
            this._alertDialog = _alertDialog;
        }
        @NonNull
        @Override
        public QuestionBankOptionVoAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_question_choose, parent, false);
            QuestionBankOptionVoAdapter.ViewHolder viewHolder = new QuestionBankOptionVoAdapter.ViewHolder(itemView);
            return viewHolder;
        }
        @Override
        public void onBindViewHolder(@NonNull QuestionBankOptionVoAdapter.ViewHolder holder, int position) {
            holder.tv_choose.setText(questionBankOptionVoList.get(position).getOptionName());
            holder.relativeLayout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    for (SupervisionInspectionContentVo inspectionContentVo : supervisionInspectionContentList) {
                        if(inspectionContentVo.getParentId().equals(supervisionInspectionContentVo.getId())){
                            for (QuestionBankOptionVo questionBankOptionVo : inspectionContentVo.getQuestionBankOptionVoList()) {
                                if(holder.tv_choose.getText().toString().equals(questionBankOptionVo.getOptionName())){
                                    inspectionContentVo.setQuestionBankOptionId(questionBankOptionVo.getId());
                                    inspectionContentVo.setBankOptionId(questionBankOptionVo.getId());//选项id
                                }
                            }
                        }
                    }
                    recyclerAdapter.notifyDataSetChanged();
                    _alertDialog.dismiss();
                }
            });
        }
        @Override
        public int getItemCount() {
            return questionBankOptionVoList.size();
        }
        class ViewHolder extends RecyclerView.ViewHolder {
            TextView tv_choose;
            ImageView image;
            RelativeLayout relativeLayout;
            public ViewHolder(View itemView) {
                super(itemView);
                this.tv_choose = itemView.findViewById(R.id.tv_choose);
                this.image = itemView.findViewById(R.id.image);
                this.relativeLayout = itemView.findViewById(R.id.relativeLayout);
            }
        }
    }

    private class QuestionTreeAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
        private List<SupervisionInspectionContentVo> supervisionInspectionContentList;
        public QuestionTreeAdapter(List<SupervisionInspectionContentVo> supervisionInspectionContentList) {
            this.supervisionInspectionContentList = supervisionInspectionContentList;
        }

        @NonNull
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            RecyclerView.ViewHolder viewHolder = getViewHolderByViewType(viewType);
            return viewHolder;
        }
        private RecyclerView.ViewHolder getViewHolderByViewType(int viewType) {
            View itemTitle = View.inflate(context,R.layout.item_question, null);
            View itemView = View.inflate(context,R.layout.item_question_tree_2, null);
            RecyclerView.ViewHolder holder=null;
            switch (viewType){
                case 0:
                    holder=new QuestionTreeAdapter.ViewHolderTitle(itemTitle);
                    break;
                case 1:
                    holder=new QuestionTreeAdapter.ViewHolderItem(itemView);
                    break;
            }
            return holder;
        }
        @Override
        public int getItemViewType(int position) {
            if(supervisionInspectionContentList.get(position).getAllowValue()==null){
                return 0;
            }else{
                return 1;
            }
        }
        @Override
        public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
            if(getItemViewType(position)==0) {
                ((QuestionTreeAdapter.ViewHolderTitle) holder).tv_question.setText(supervisionInspectionContentList.get(position).getQuestionName());
            }
            if(getItemViewType(position)==1){
                SupervisionInspectionContentVo supervisionInspectionContentVo=supervisionInspectionContentList.get(position);
                ((QuestionTreeAdapter.ViewHolderItem)holder).tv_question.setText(supervisionInspectionContentVo.getQuestionName());
                supervisionInspectionContentList.get(position).setQuestionBankId(supervisionInspectionContentVo.getId());
                List<InspectResultVo> inspectResultVoList = supervisionInspectionVo.getInspectResultVoList();
                if(inspectResultVoList!=null){
                    for (InspectResultVo inspectResultVo : inspectResultVoList) {
                        if(supervisionInspectionContentList.get(position).getId().equals(inspectResultVo.getQuestionBankId())){
                            supervisionInspectionContentVo.setBankOption(inspectResultVo.getBankOption());
                            break;
                        }
                    }
                }else{//赋值默认值
                    if(!StringUtil.isNullOrEmpty(supervisionInspectionContentVo.getDefaultValue())){
                        supervisionInspectionContentVo.setBankOption(supervisionInspectionContentVo.getDefaultValue());
                    }
                }
                if(!StringUtil.isNullOrEmpty(supervisionInspectionContentVo.getBankOption())){
                    ((QuestionTreeAdapter.ViewHolderItem)holder).tv_answer.setText(AnswerUtil.setAnswer(supervisionInspectionContentVo.getBankOption()));
                    ((QuestionTreeAdapter.ViewHolderItem)holder).tv_answer.setTextColor(getResources().getColor(R.color.header));
                }
                if(isQualified()){
                    rb_status_1.setChecked(true);
                    supervisionInspectionVo.setInspectResult("1");
                }else{
                    rb_status_2.setChecked(true);
                    supervisionInspectionVo.setInspectResult("0");
                }
                ((QuestionTreeAdapter.ViewHolderItem)holder).linearLayout.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        showChoose(((QuestionTreeAdapter.ViewHolderItem)holder).tv_answer,supervisionInspectionContentList.get(position).getEnforceBasisId(),
                                supervisionInspectionContentList.get(position).getId(),
                                supervisionInspectionContentList.get(position).getAllowValue());
                    }
                });
            }
        }
        @Override
        public int getItemCount() {
            return supervisionInspectionContentList.size();
        }

        class ViewHolderTitle extends RecyclerView.ViewHolder {
            TextView tv_question;
            public ViewHolderTitle(View itemView) {
                super(itemView);
                tv_question = (TextView) itemView.findViewById(R.id.tv_question);
            }
        }
        class ViewHolderItem extends RecyclerView.ViewHolder {
            TextView tv_question,tv_answer;LinearLayout linearLayout;
            public ViewHolderItem(View itemView) {
                super(itemView);
                tv_question = (TextView) itemView.findViewById(R.id.tv_question);
                tv_answer = (TextView) itemView.findViewById(R.id.tv_answer);
                linearLayout =(LinearLayout) itemView.findViewById(R.id.linearLayout);
            }
        }
    }

    private void showChoose(TextView textView,String enforceBasisId,String questionId,String allowValue) {
        LayoutInflater mLayoutInflater = LayoutInflater.from(this);
        View view = mLayoutInflater.inflate(R.layout.dialog_is_fit, null);
        final AlertDialog.Builder alertBuilder = new AlertDialog.Builder(context, R.style.ActionSheetDialogStyle);
        alertBuilder.setView(view);
        _alertDialog = alertBuilder.create();
        //获取当前Activity所在的窗体
        Window window = _alertDialog.getWindow();
        window.setGravity(Gravity.BOTTOM);
        _alertDialog.show();
        ImageView iv_dismiss = (ImageView) view.findViewById(R.id.iv_dismiss);
        RecyclerView rv_question_answer = (RecyclerView) view.findViewById(R.id.rv_question_answer);
        LinearLayoutManager layoutManage = new LinearLayoutManager(context);
        rv_question_answer.setLayoutManager(layoutManage);
        if(!StringUtil.isNullOrEmpty(allowValue)){
            String[] answers = allowValue.split(","); // 使用逗号作为分隔符进行切割
            QuestionBankOptionAdapter recyclerAdapter=new QuestionBankOptionAdapter(textView,enforceBasisId,questionId,_alertDialog,answers);
            rv_question_answer.setAdapter(recyclerAdapter);
        }
        iv_dismiss.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                _alertDialog.dismiss();
            }
        });
        WindowManager.LayoutParams params = window.getAttributes() ;
        params.width =(int) (getWindowManager().getDefaultDisplay().getWidth());                     //使用这种方式更改了dialog的框宽
        window.setAttributes(params);
    }

    public class QuestionBankOptionAdapter extends RecyclerView.Adapter<QuestionBankOptionAdapter.ViewHolder> {
        private String[] answers;
        private TextView textView;private String enforceBasisId,questionId;
        private AlertDialog _alertDialog;
        private int checkPosition=-1;
        public QuestionBankOptionAdapter(TextView textView,String enforceBasisId,String questionId, AlertDialog _alertDialog,String[] answers) {
            this.answers = answers;
            this._alertDialog = _alertDialog;
            this.textView = textView;
            this.enforceBasisId=enforceBasisId;
            this.questionId=questionId;
        }
        @Override
        public QuestionBankOptionAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_question_choose, parent, false);
            QuestionBankOptionAdapter.ViewHolder viewHolder = new QuestionBankOptionAdapter.ViewHolder(itemView);
            return viewHolder;
        }

        @Override
        public void onBindViewHolder(@NonNull QuestionBankOptionAdapter.ViewHolder holder, int position) {
            holder.tv_choose.setText(AnswerUtil.setAnswer(answers[position]));
            if(AnswerUtil.setAnswer(answers[position]).equals(textView.getText().toString())){
                holder.image.setVisibility(View.VISIBLE);
            }else{
                if(answers[position].equals("1")&&textView.getText().toString().equals("请选择")){
                    holder.image.setVisibility(View.VISIBLE);
                }else{
                    holder.image.setVisibility(View.GONE);
                }
            }

            holder.relativeLayout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    for (SupervisionInspectionContentVo supervisionInspectionContentVo : supervisionInspectionContentList) {
                        if(supervisionInspectionContentVo.getId().equals(questionId)){
                            supervisionInspectionContentVo.setBankOption(answers[position]);
                            break;
                        }
                    }
                    textView.setText(AnswerUtil.setAnswer(answers[position]));
                    textView.setTextColor(getResources().getColor(R.color.header));
                    holder.image.setVisibility(View.VISIBLE);
                    _alertDialog.dismiss();
                    checkPosition=position;
                    notifyDataSetChanged();
                    if(answers[position].equals("2")){
                        if(!StringUtil.isNullOrEmpty(enforceBasisId)){
                            getEnforceBasisById(enforceBasisId);
                        }else{
                            startActivity(new Intent(context, DailyCheckContentActivity.class));
                        }
                    }
                    if(isQualified()){
                        rb_status_1.setChecked(true);
                        supervisionInspectionVo.setInspectResult("1");
                    }else{
                        rb_status_2.setChecked(true);
                        supervisionInspectionVo.setInspectResult("0");
                    }
                }
            });

            if(position==checkPosition){
                holder.image.setVisibility(View.VISIBLE);
            }else{
                if(checkPosition!=-1){
                    holder.image.setVisibility(View.GONE);
                }
            }
        }

        @Override
        public int getItemCount() {
            return answers.length;
        }

        class ViewHolder extends RecyclerView.ViewHolder {
            TextView tv_choose;ImageView image;
            RelativeLayout relativeLayout;
            public ViewHolder(View itemView) {
                super(itemView);
                this.tv_choose = itemView.findViewById(R.id.tv_choose);
                this.image = itemView.findViewById(R.id.image);
                this.relativeLayout = itemView.findViewById(R.id.relativeLayout);
            }
        }
    }

    public boolean isQualified(){
        for (SupervisionInspectionContentVo supervisionInspectionContentVo : supervisionInspectionContentList) {
            if("2".equals(supervisionInspectionContentVo.getBankOption())){//不合格
                return false;
            }
        }
        return true;
    }

    /*获取详情失败*/
    private void getEnforceBasisById(String id){
        Retrofit retrofit = UtilHelper.retrofit(application, UtilHelper.baseUrls.API());//URL的头
//        Retrofit retrofit = UtilHelper.retrofit(application, "http://192.168.1.69:9004/");//URL的头
        SupervisionService vs = retrofit.create(SupervisionService.class);
        Map<String, String> params = ParamsMapUtil.getInstance("id",(id==null)?"":id);
        Call<JsonForResult> jsonForResultCall = vs.getEnforceBasisById(application.getAccessToken(),params);//调用接口获取json返回
        jsonForResultCall.enqueue(new Callback<JsonForResult>() {
            @Override
            public void onResponse(Call<JsonForResult> call, Response<JsonForResult> response) {
                try {
                    JsonForResult jsonForResult = response.body();
                    if (jsonForResult != null && jsonForResult.isSuccess()) {
                        if(jsonForResult.getData()!=null){//如果有数据，将数据带过去显示
                            IllegalRecordDtlVo illegalRecordDtlVo = JSON.parseObject(jsonForResult.getData().toString(), IllegalRecordDtlVo.class);
                            Intent intent;
                            if(!StringUtil.isNullOrEmpty(illegalRecordDtlVo.getHandleBasis())&&!StringUtil.isNullOrEmpty(illegalRecordDtlVo.getSuperviseOpinion())&&
                                    !StringUtil.isNullOrEmpty(illegalRecordDtlVo.getIllegalBehavior())&&!StringUtil.isNullOrEmpty(illegalRecordDtlVo.getQualitativeBasis())){
                                intent = new Intent(context, DailyStandardWordActivity.class);
                                Gson gson = new Gson();
                                intent.putExtra("enforceBasis",gson.toJson (jsonForResult.getData()));
                            }else{//是标题项的
                                intent = new Intent(context, DailyCheckContentActivity.class);
                                intent.putExtra("code", illegalRecordDtlVo.getCode());
                            }
                            context.startActivity(intent);
                        }else{//如果没数据，就到页面全盘选择
                            Intent intent=new Intent(context, DailyCheckContentActivity.class);
                            context.startActivity(intent);
                        }
                    }
                } catch (Exception e) {
                    UtilHelper.alertMsg(context, "错误", e.getMessage());
                }
            }
            @Override
            public void onFailure(Call<JsonForResult> call, Throwable t) {
                String msg = "网络错误!";
                UtilHelper.alertMsg(context, "错误", msg);
            }
        });
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}